﻿//   -------------------- iSharePoint -------------------- //
//  
//   Company:	IT Complex, LLC
//   Project:	Smart.Common
//   File name:	SPFolderExts.cs
//   Developer:	Игорь Соломатов
//   Created:	28.08.2012
//  
//   -------------------- iSharePoint -------------------- //

using System;
using System.Diagnostics;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Smart.Common
{
	[DebuggerStepThrough]
	public static class SPFolderExts
	{
		/// <summary>
		/// Returns file in <paramref name="folder"/> by <paramref name="fileName"/>
		/// </summary>
		public static SPFile GetFile(this SPFolder folder, string fileName)
		{
			try
			{
				return folder.Files[fileName];
			}
			catch (Exception x)
			{
				H.LX("SPFolderExts.GetFile", x);
			}

			return null;
		}

		/// <summary>
		/// Returns sub folder in <paramref name="folder"/> by <paramref name="folderName"/>
		/// </summary>
		public static SPFolder GetSubFolder(this SPFolder folder, string folderName)
		{
			try
			{
				return folder.SubFolders[folderName];
			}
			catch (Exception x)
			{
				H.LX("SPFolderExts.GetSubFolder", x);
			}

			return null;
		}

		/// <summary>
		/// Returns sub folder in <paramref name="rootFolder"/> by <paramref name="folderPath"/>, <paramref name="create"/> non-existing folders if specified
		/// </summary>
		public static SPFolder GetFolderByPath(this SPFolder rootFolder, bool create, params string[] folderPath)
		{
			SPFolder current = null;

			try
			{
				current = rootFolder;

				for (var I = 0; (I < folderPath.Length) && (current != null); I++)
				{
					var folderName = folderPath[I].RemoveSpcChars();

					if (folderName.IsNullOrEmpty()) continue;

					var folder = current.GetSubFolder(folderName);

					if (create && folder == null)
					{
						// Создаем папку
						try
						{
							folder = current.SubFolders.Add(folderName);
						}
						catch (Exception x)
						{
							H.LX("GetFolderByPath.C", x);
							folder = null;
						}
					}

					current = folder;
				}
			}
			catch (Exception x)
			{
				H.LX("GetFolderByPath", x);
			}

			return current;
		}

		/// <summary>
		/// Returns full folder url
		/// </summary>
		public static string GetFullUrl(this SPFolder folder)
		{
			return SPUrlUtility.CombineUrl(folder.ParentWeb.Url, folder.Url);
		}

		/// <summary>
		/// Returns web-relative folder url
		/// </summary>
		public static string GetWebRelativeUrl(this SPFolder folder)
		{
			return folder.Url.TrimStart('/');
		}

		/// <summary>
		/// Returns server-relative folder url
		/// </summary>
		public static string GetServerRelativeUrl(this SPFolder folder)
		{
			return folder.ServerRelativeUrl;
		}
	}
}